# 官方示例：https://docs.openstack.org/python-glanceclient/queens/reference/apiv2.html#delete

from keystoneauth1.identity import v3
from keystoneauth1 import session
from glanceclient import Client

host = "192.168.112.201"

auth = v3.Password(auth_url="http://{}:5000/v3".format(host),
                   username="admin", password="000000",
                   project_name="admin", user_domain_name="demo",
                   project_domain_name="demo")
sess = session.Session(auth=auth)
glance = Client('2', "http://{}:9292".format(host), session=sess)


def create(name):
    return glance.images.create(name=name, disk_format="qcow2", container_format="bare", is_public="true")


def upimg(img_id, filename):
    glance.images.upload(img_id, open(filename, 'rb'))


def delete(img_id):
    glance.images.delete(img_id)


def get_images():
    list = glance.images.list()
    for image in list:
        print(image.name, image.status, image.id)


def get_image(img_id):
    return glance.images.get(img_id)


def down_image(img_id):
    with open('./cirros-0.3.5-x86_64-disk.img', 'wb') as f:
        for chunk in glance.images.data(img_id):
            f.write(chunk)


# 创建镜像 print(upimg(create("123").id,"cirros-0.3.5-x86_64-disk.img"))
# 获取镜像信息 print(get_image("1bb062ec-c3db-4f81-8ce1-08d7b4045e24"))
# 删除镜像 delete("1bb062ec-c3db-4f81-8ce1-08d7b4045e24")
# 获取镜像列表 get_images()
# 下载镜像 down_image("4904cad4-93dd-4437-b749-9939155f5c07")

